<?php

// +----------------------------------------------------------------------
// | 版权所有 2017-2027 云南环拓科技有限公司，并保留所有权利。
// +----------------------------------------------------------------------
// | Copyright (c) 2017-2027 http://www.yn123.com All rights reserved.
// +----------------------------------------------------------------------
// | Notice: This code is not open source, it is strictly prohibited
// |         to distribute the copy, otherwise it will pursue its
// |         legal responsibility.
// | 注意：  这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用,
// |        不允许对程序代码以任何形式任何目的的再发布。
// +----------------------------------------------------------------------
// | Author: feraner <feraner@163.com> 
// | Date: 2019/12/19
// +----------------------------------------------------------------------

namespace app\index\controller\api;

use app\common\constants\ApiConstant;
use app\common\facade\Arr;
use app\common\services\MarketPublishService;
use app\common\services\MarketService;
use app\common\services\UserService;
use app\common\validate\MarketGoodsValidate;
use think\App;
use think\Db;

/**
 *
 * Class Market
 * @package app\index\controller\api
 * @author feraner<feraner@163.com>
 * @date 2019/12/19
 */
class Market extends ApiBase
{

    public function __construct(App $app = null)
    {
        parent::__construct($app);
    }


    /**
     * 二手商品列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function goodsList()
    {
        $postData = $this->request->param();
        //地区
        if ($areaValue = Arr::get($postData, 'areaValue', '')) {
            $areaArr = array_filter(explode('|', str_replace(['镇', '县', '乡', '村', '庄', '市','省'], '', $areaValue)));
            if (Arr::get($areaArr, 0, '')) {
                $provincesId = Db::name('area')
                    ->where('area_name', 'LIKE', '%' . Arr::get($areaArr, 0) . '%')
                    ->where('area_deep', 1)
                    ->value('area_id') ?: 0;
                if ($provincesId) {
                    $postData['provincesId'] = $provincesId;
                }
            }
            if (Arr::get($areaArr, 1)) {
                $cityId = Db::name('area')
                    ->where('area_name', 'LIKE', '%' . Arr::get($areaArr, 1) . '%')
                    ->where('area_deep', 2)
                    ->where('area_parent_id', Arr::get($postData, 'provincesId', 0))
                    ->value('area_id') ?: 0;
                if ($cityId) {
                    $postData['cityId'] = $cityId;
                }
            }
            if (Arr::get($areaArr, 2)) {
                $countyId = Db::name('area')
                    ->where('area_name', 'LIKE', '%' . Arr::get($areaArr, 2) . '%')
                    ->where('area_deep', 3)
                    ->where('area_parent_id', Arr::get($postData, 'cityId', 0))
                    ->value('area_id') ?: 0;
                if ($countyId) {
                    $postData['countyId'] = $countyId;
                }
            }
            $postData = $this->checkLocationInSystem($postData);
        }

        $goodsList = (new MarketService())->goodsList(
            $postData,
            Arr::get($postData, 'page'),
            Arr::get($postData, 'pageSize'),
            []
        );


        $this->response([
            'goodsList'          => $goodsList
        ]);

    }


    /**
     * 二手商品详情
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function goodsDetail()
    {
        $goodsId = $this->request->param('id');
        $extend = $this->request->param('extend', 'content', 'trim');
        $extend = array_filter(explode(',', $extend));
        if ($goodsId) {
            $goodsInfo = (new MarketService())->goodsDetail($goodsId, $extend);
            if ($goodsInfo) {
                //把封面放入到图片展示中
                array_unshift($goodsInfo['imageArr'], Arr::get($goodsInfo, 'logo', ''));
                $goodsInfo['userCollect'] = (new UserService())->isCollect($goodsId, $this->userId, 2);
                Db::name('market')
                    ->where('id', $goodsId)
                    ->setInc('click_num');
                $this->response($goodsInfo);
            }
            $this->response(
                [],
                ApiConstant::MARKET_NOT_FUND_ERROR,
                ApiConstant::MARKET_NOT_FUND_ERROR_STR
            );
        }
        $this->response(
            [],
            ApiConstant::API_PARAMETER_ERROR,
            ApiConstant::API_PARAMETER_ERROR_STR
        );
    }


    /**
     * 发布兼职保存为草稿
     */
    public function saveGoodsDraft()
    {
        $postData = $this->request->post();
        $goodsValidate = new MarketGoodsValidate();
        if ($goodsValidate->check($postData)) {
            $postData = array_merge(
                $postData,
                [
                    'publish_id'    => $this->userId,
                    'status'        => 1,
                    'type'          => 0,
                    'aid'           => 0,
                ]
            );
            try {
                $result = (new MarketPublishService())->saveMarketGoodsDraft($postData);
            } catch (\Exception $e) {
                $this->response(
                    [],
                    ApiConstant::MARKET_SAVE_DRAFT_ERROR,
                    ApiConstant::MARKET_SAVE_DRAFT_ERROR_STR . $e->getMessage()
                );
            }
            if ($result) {
                $this->response(
                    $result,
                    ApiConstant::API_SUCCESS,
                    ApiConstant::API_SUCCESS_STR
                );
            }
            $this->response(
                [],
                ApiConstant::MARKET_SAVE_DRAFT_ERROR,
                ApiConstant::MARKET_SAVE_DRAFT_ERROR_STR
            );
        } else {
            $this->response(
                [],
                ApiConstant::PARAMETER_NOT_PASS,
                ApiConstant::PARAMETER_NOT_PASS_STR . $goodsValidate->getError()
            );
        }
    }


    /**
     * 发布二手商品 [需要审核]
     */
    public function publishGoods()
    {
        $postData = $this->request->post();

        $goodsValidate = new MarketGoodsValidate();
        if ($goodsValidate->check($postData)) {
            $postData = array_merge(
                $postData,
                [
                    'publish_id'    => $this->userId,
                    'status'        => 2,
                    'type'          => 0,
                    'aid'           => 0,
                ]
            );
            try {
                $result = (new MarketPublishService())->publishMarketGoods($postData);
                if ($result) {
                    $this->response(
                        $result,
                        ApiConstant::API_SUCCESS,
                        ApiConstant::API_SUCCESS_STR
                    );
                }
            } catch (\Exception $e) {
                $this->response(
                    [],
                    ApiConstant::MARKET_PUBLISH_ERROR,
                    ApiConstant::MARKET_PUBLISH_ERROR_STR . $e->getMessage()
                );
            }
        } else {
            $this->response(
                [],
                ApiConstant::PARAMETER_NOT_PASS,
                ApiConstant::PARAMETER_NOT_PASS_STR . $goodsValidate->getError()
            );
        }
    }






    /**
     * 二手商品列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function marketType()
    {
        $limit = $this->request->param('limit', 100);
        $typeListDb = Db::name('market_type')
            ->where('status', 1);
        if ($limit) {
            $typeListDb->limit(0, $limit);
        }
        $typeList = $typeListDb->order('sort', 'ASC')
            ->select() ?: [];
        if ($typeList) {
            $this->response($typeList);
        }
        $this->response([], ApiConstant::JOB_TYPE_IS_NOT_FUND, ApiConstant::JOB_TYPE_IS_NOT_FUND_STR);
    }















}
